import {
  Tag, Descriptions, DatePicker,
  Upload, Input, Button, InputNumber, message, Spin, Select
} from "antd"
import { useEffect, useState } from "react";
import { AddSupplier } from "../../api/supplier";
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { AddMerchant } from "../../api/merchant";
import dayjs from "dayjs";
import { AddGoods, getGoodsTypes } from "../../api/goods";
//新增商品
const AddGood = () => {
  document.info = [
    {
      title: "新增商品",
      url: "/goods",
  },
    {
        title: "商品管理",
        url: "/goods",
    }
  ]
  const [users, setUser] = useState({
    names: "",
    type: "",
    price: 1.00,
    specs: "",
    date: "",
    expiryday: "",
    remark: "",
    imgs: ""
  });
  const { TextArea } = Input;
  const [loading, setLoading] = useState(false);
  const [spinloading,setSpinLoading]=useState(false);
  const [options,setOptions]=useState([]);
  const [imageUrl, setImageUrl] = useState();
  const data={
    // options:[
    //   {
    //     value: '粮油米面',
    //     label: '粮油米面',
    //   },
    //   {
    //     value: '蔬菜生鲜',
    //     label: '蔬菜生鲜',
    //   },
    //   {
    //     value: '海鲜肉类',
    //     label: '海鲜肉类',
    //   }
    // ]
  }
  //获取商品名称
  const getName = (e) => {
    setUser((users) => ({ ...users, names: e.target.value }));
  }

  //类型改变事件
  const handleChange = (value) => {
    setUser((users) => ({ ...users, type: value }));
   
  }

  //价格改变事件
  const onChange = (value) => {
    setUser((users) => ({ ...users, price: value }));
  };
  //保质期改变事件
  const onChangeDay = (value) => {
    setUser((users) => ({ ...users, expiryday: value }));
  }

  //生产日期
  const DateonChange = (value) => {
    setUser((users) => ({ ...users, date: dayjs(value).format("YYYY-MM-DD") }));

  }

  //规格改变事件
  const getSpecs = (value) => {
    setUser((users) => ({ ...users, specs: value.target.value }));
  }


  //描述改变事件
  const getRemark = (value) => {
    setUser((users) => ({ ...users, remark: value.target.value }));
  }



     //上传使用
     const uploadButton = (
      <button
        style={{
          border: 0,
          background: 'none',
        }}
        type="button"
      >
        {loading ? <LoadingOutlined /> : <PlusOutlined />}
        <div
          style={{
            marginTop: 8,
          }}
        >
          Upload
        </div>
      </button>
    );


  const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);

  };
  const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  };

  //   const [loading, setLoading] = useState(false);


  const uploadHandleChange = (info) => {
    if(info.file.response){
      setUser((users) => ({ ...users, imgs: info.file.response}));
    }
    if (info.file.status === 'uploading') {
     
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, (url) => {
       
        setLoading(false);
        setImageUrl(url);
      });
    }
  }







  //描述列表
  const items = [
    {
      key: '1',
      label: '商品名称',
      span: 1.5,
      children:
        <Input onChange={(e) => getName(e)}></Input>
    },
    {
      key: '2',
      label: '类型',
      span: 1.5,
      children: <Select
        placeholder="请选择商品类型"

        style={{
          width: "100%",
        }}
        onChange={handleChange}
        options={options}
      >

      </Select>
    },
    {
      key: '3',
      label: '价格',
      span: 1.5,
      children: <InputNumber
        min={0}
        defaultValue={1.00}
        step="1.00" stringMode
        onChange={onChange}
        style={{ width: "100%" }} />
    },
    {
      key: '4',
      label: '规格',
      span: 1.5,
      children: <Input onChange={(e) => getSpecs(e)}></Input>
    },
    {
      key: '5',
      label: '生产日期',
      span: 1.5,
      children: <DatePicker onChange={DateonChange} />
    },
    {
      key: '6',
      label: '保质期(天)',
      span: 1.5,
      children: <InputNumber
        min={1}
        defaultValue={1}
        onChange={onChangeDay}
        style={{ width: "100%" }} />
    }
    ,
    {
      key: '7',
      label: '描述',
      span: 3,
      children: <TextArea onChange={(e) => getRemark(e)} rows={4}></TextArea>
    },
    {
      key: '8',
      label: '封面',
      span: 3,
      children: <Upload
        name="avatar"
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        action="https://sapi.jiangdaye.cn/api/Resource/Upload"
        beforeUpload={beforeUpload}
        onChange={uploadHandleChange}
      >
        {imageUrl ? (
          <img
            src={imageUrl}
            alt="avatar"
            style={{
              width: '100%',
            }}
          />
        ) : (
          uploadButton
        )}
      </Upload>
    },
    {
      key: '9',
      label: '操作',
      span: 3,
      children: <Button type="primary" onClick={() => { addSupplier() }}>新增</Button>
    }

  ]
  
  const methods={
    /**
     * 获取商品类型
     */
     getGoodsTypes:async()=>{
      const res=await getGoodsTypes({
        page:1,
        limit:999,
        key:"",
        isDirectly:true
      });
      if(res.result===0){
        const data=res.data.data.map((d)=>({value:d.id,label:d.name}));
        setOptions(data);
      }
    }
  }


  
  const addSupplier = async () => {
    setSpinLoading(true);
    
    if(!users.imgs){
      message.error("请上传正确得图片");
      setSpinLoading(false);
      return
    }
   
   const  res=await AddGoods({
      birthday:users.date,
      expiryday:users.day,
      name:users.names,
      explain:users.remark,
      price:users.price,
      specs:users.specs,
      photo:users.imgs,
      type:users.type
    })
    
    if(res.result===0){
      message.success("操作成功");
      setSpinLoading(false);
    }else{
      message.error(res.message);
      setSpinLoading(false);
    }
   

  }


  useEffect(()=>{
    methods.getGoodsTypes();
  },[])

  return (
    <>
      <div className="Containers">
      <Spin
                    spinning={spinloading}
                    indicator={
                        <LoadingOutlined
                            style={{
                                fontSize: 24,
                            }}


                        />
                    }
                >
        <div className="pws">
          <Descriptions title="新增商品" layout="vertical" bordered items={items} />
        </div>
        </Spin>
      </div>
    </>
  )
}

export default AddGood